package top.revery.task.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import top.revery.api.entity.user.BaseUserWorks;
import top.revery.task.dto.UserWorksDto;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Map;

/**
 * @author denghao
 * @title
 * @package
 * @date 2019/12/13 18:08
 */
@Service
public class UserWorksService {
    @Autowired
    private UserWorksDto userWorksDto;
   // @GlobalTransactional
    public Page<BaseUserWorks> findPage(int pageNum, int pageSize, Map map) {
        Specification<BaseUserWorks> specification = createSpecification(map);
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        return userWorksDto.findAll(specification, pageRequest);
    }
    private Specification<BaseUserWorks> createSpecification(Map map) {
        return new Specification<BaseUserWorks>() {
            @Override
            public Predicate toPredicate(Root<BaseUserWorks> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                //id
                if (map.get("id") != null && !"".equals(map.get("id"))) {
                    predicate.getExpressions().add(cb.equal(root.get("id"), map.get("id")));
                }
              /*  if (map.get("name") != null && !"".equals(map.get("name"))) {
                    predicate.getExpressions().add(cb.like(root.get("name"),"%"+(String)map.get("name")+"%"));
                }*/
                //用户查询
                if (map.get("redId") != null && !"".equals(map.get("redId"))) {
                    predicate.getExpressions().add(cb.equal(root.get("redId"), map.get("redId")));
                }
              /*  if (map.get("type") != null && !"".equals(map.get("type"))) {
                    predicate.getExpressions().add(cb.equal(root.get("type"), map.get("type")));
                }*/
                return predicate;
            }
        };
    }
}
